import { useStore as useUserStore } from "@/store/user";
import jwtSign from "@/common/jwt";
import { showToast } from '@nutui/nutui';
import '@nutui/nutui/dist/packages/toast/style';
import router from "@/router";
import _ from "lodash";
export default class apibase {
  
  constructor() {

  }
  // api请求公共方法
  base(instance: any, mock: boolean) {
    instance.defaults.baseURL = mock ? '/mock' : process.env.VUE_APP_BASE_API;
    /**
     * @Auther: 罗耀祖
     * @LastEditors: 罗耀祖
     * @description: 请求拦截添加公共参数
     */
    instance.interceptors.request.use((config: any) => {
      config.timeout = 600000;
      return config;
    })
    /**
     * @Auther: 罗耀祖
     * @LastEditors: 罗耀祖
     * @description: 回传拦截处理回传内容
     */
    instance.interceptors.response.use((response: any) => {
      let res = { code: response.data.code, msg: response.data.msg, data: response.data.data };
      return this.matchRes(res);
    }, (error: any) => {
      error = JSON.parse(JSON.stringify(error));
      if (error?.response) {
        console.error(error);
      } else {
        showToast.fail(error.message);
      }
      return Promise.reject(error);
    })
  }
  // res 回传结果, async 是否异步
  matchRes = (res: any, async: Boolean = true) => {
    if (res.code === 200) {
      return res;
    } else if (res.code === 401) {
      const userStore = useUserStore();
      userStore.logout();
      router.replace('/login');
      return async ? Promise.reject(res) : res;
    } else if (res.code === 400) {
      showToast.fail(res.msg);
      return async ? Promise.reject(res) : res;
    } else if (res.code === 403) {
      showToast.fail(res.msg);
      return async ? Promise.reject(res) : res;
    } else if (res.code === 500) {
      return async ? Promise.reject(res) : res;
    } else {
      return async ? Promise.reject(res) : res;
    }
  }
  //type: jwt验签请求   upload:上传
  get({ url, instance, data, type = "jwt", mock = false }: { url: string, instance: any, data: any, type?: string, mock?: boolean }) {
    instance.interceptors.request.use((config: any) => {
      if (type === "jwt") {
        const userStore = useUserStore();
        const token = userStore.token;
        const uid =  userStore.uid;
        let Authorization: any = {
          uid,
          iat: (new Date().getTime() / 1000).toFixed(0),
          token,
          ...data,
        };
        Authorization = jwtSign(Authorization);
        config.headers.Authorization = Authorization;
      }
      return config;
    });
    this.base(instance, mock);
    return instance.get(url, { params: data });
  }
  //type: jwt验签请求   upload:上传
  post({ url, instance, data, type = "jwt", mock = false,formData}: { url: string, instance: any, data: any, type?: string, mock?: boolean,formData?:any}) {
    const mData = _.cloneDeep(data);
    instance.interceptors.request.use((config: any) => {
      if (type === "jwt") {
        const userStore = useUserStore();
        const token = userStore.token;
        const uid =  userStore.uid;
        let Authorization: any = {
          uid,
          iat: (new Date().getTime() / 1000).toFixed(0),
          token,
          ...mData,
        };
        Authorization = jwtSign(Authorization);
        config.headers.Authorization = Authorization;
      }
      return config;
    });
    this.base(instance, mock);
    if(formData)
    {
      const form = new FormData();
      Object.entries(data).forEach((item:any) =>{
         form.append(item[0],item[1]);
      })
      Object.entries(formData).forEach((item:any) =>{
        form.append(item[0],item[1]);
     })
     data = form;
    }

    return instance.post(url, data);
  }
}